package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.PDetailsRepository;
import com.chz.SupermarketMS.dto.CommodityPD;
import com.chz.SupermarketMS.entities.Commodity;
import com.chz.SupermarketMS.entities.PDetails;
import com.chz.SupermarketMS.entities.Purchase;
import com.chz.SupermarketMS.service.CommodityService;
import com.chz.SupermarketMS.service.PDetailsService;
import com.chz.SupermarketMS.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("pDetails")
public class PDetailsController {

    @Autowired
    PDetailsService pDetailsService;

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    CommodityService commodityService;

    @Autowired
    PDetailsRepository pDetailsRepository;

    @GetMapping
    public String displayPDetails(Model model){

        List<PDetails> pDetails = pDetailsService.getAll();
        model.addAttribute("pDetails",pDetails);

        List<CommodityPD> commodityPDS= pDetailsRepository.commodityPD();
        model.addAttribute("commodityPD",commodityPDS);

        return "pDetails/list-pDetails";
    }

    @GetMapping("/new")
    public String displayPDetailsForm(Model model){
        PDetails aPDetails = new PDetails();
        List<Purchase> purchases = purchaseService.getAll();
        List<Commodity> commodities = commodityService.getAll();
        model.addAttribute("allCommodities",commodities);
        model.addAttribute("allPurchases",purchases);
        model.addAttribute("pDetails",aPDetails);

        return "pDetails/new-pDetails";
    }

    @PostMapping("/save")
    public String createPDetails(Model model, @RequestParam List<Long> commodities,  PDetails pDetails){

            pDetailsService.save(pDetails);

        return "redirect:/pDetails";
    }
    @GetMapping("/update")
    public String displayPDetailsUpdateForm(@RequestParam("id") long theId, Model model) {
        PDetails thePDetails = pDetailsService.findByPdId(theId);
        model.addAttribute("pDetails", thePDetails);
        return "pDetails/new-pDetails";
    }
    @GetMapping("/delete")
     public String deletePDetails(@RequestParam("id")long theId, Model model) {
        PDetails thePDetails = pDetailsService.findByPdId(theId);
        pDetailsService.delete(thePDetails);
       return "redirect:/pDetails";
    }

}
